export async function request(topic: String, payload: Object | null) {
    if (topic == null) {
        console.error("topic can not null")
        return
    }
    const msgInfo = {
        msgId: uuid(),
        topic: topic,
        payload: payload,
        gmtEvent: new Date()
    }
    console.debug("sendMsg:", msgInfo)
    window.appBridge.onEmit(topic, msgInfo)
    let response = await new Promise((resolve, reject) => {
        window.appBridge.onListen(topic + msgInfo.msgId, (response) => {
            if (response.success == false) {
                console.warn(response)
            }
            console.debug("reciveMsg:", response)
            resolve(response)
        })
    })

    return response
}




export function onEmit(topic: String, payload?: Object) {
    if (topic == null) {
        console.error("topic can not null")
        return
    }
    const msgInfo = {
        msgId: uuid(),
        topic: topic,
        payload: payload,
        gmtEvent: new Date()
    }
    console.debug("onEmit:", msgInfo)

    window.appBridge.onEmit(topic, msgInfo)
}


export function onListen(topic: String, callback: Function) {
    if (topic == null) {
        console.error("topic can not null")
        return
    }
    if (callback == null) {
        console.error("callback can not null")
        return
    }
    console.debug("onListenTopic:", topic)
    window.appBridge.onListen(topic, (response: Object) => {
        if (response.success == false) {
            console.warn(response)
        }
        console.debug("reciveMsg:", response)
        if (callback) {
            callback(response)
        }
    })
}



function uuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}